// pages/device.js
const ecUI = require('../../utils/ecUI.js')
const ecBLE = require('../../utils/ecBLE.js')

const { dec2hex,
  endianConv,
  hexCharCodeToStr,
  stringToHex,
  convertSecondsToHMS,
  hexStringToByteArray,
  dateFormat,
  formatTime
} = require('../../utils/util.js')

const { crc16 } = require('../../utils/crc-16.js')

const logEnable = true

function log(...args) {
  if (logEnable) {
    console.log(...args);
  }
}


let ctx
let isCheckScroll = true
let isCheckRevHex = true
let isCheckSendHex = true
let sendData = ''

let focus = false
let startTimeStamp = new Date().getTime()

let T1 = null

Page({
    /**
     * 页面的初始数据
     */
    data: {
        id: '',
        textRevData: '',
        scrollIntoView: 'scroll-view-bottom',

        updataHex: null, //string格式的数据放这里
        totalCount: 0,
        curPkg: 0,
        percentage: 0,
        isLink: false,
        isTranslate: false,
        chooseFile: null
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        // console.log(crc16('55CC00000238B00B190100000000')) // 7112
        // console.log(crc16('55AA000002480BB0800C0F4101FF')) // 92F3
        
        this.setData({
            id: options.id,
        })
        ctx = this
        isCheckScroll = true
        isCheckRevHex = true
        isCheckSendHex = true
        // sendData = ''
        // ecBLE.setChineseType(ecBLE.ECBLEChineseTypeGBK)
        ecBLE.setChineseType(ecBLE.ECBLEChineseTypeUTF8)



    },
    onShow() {
        // wx.setStorageSync('localPwd', '12345678');
        ctx = this
        focus = false
        sendData = ''
        //on disconnect
        ecBLE.onBLEConnectionStateChange(ctx.bleStateChange)
        //receive data
        ecBLE.onBLECharacteristicValueChange(ctx.bleValueChange)
    },
    bleStateChange() {
        ecUI.showModal('提示', '设备断开连接', ()=> {
            log('reLaunch')
            wx.reLaunch({
                url: '/pages/index/index',
            })
        })
    },
    bleValueChange(str, strHex) {

            let data =
                ctx.data.textRevData +
                dateFormat('[hh:mm:ss,S]:', new Date()) +
                (isCheckRevHex ? strHex.replace(/[0-9a-fA-F]{2}/g, ' $&') : str) +
                '\r\n'
            // console.log(data)
            ctx.setData({ textRevData: data })
                if (ctx.data.scrollIntoView === "scroll-view-bottom") {
                    ctx.setData({ scrollIntoView: "scroll-view-bottom2" })
                } else {
                    ctx.setData({ scrollIntoView: "scroll-view-bottom" })
                }
   


        let end = new Date().getTime()
        // const flag = (end - startTimeStamp) < 240
        const flag = (end - startTimeStamp) > 300
        if (focus || flag) return

        // mark


        //    const strHex = '55AA00000248B00B800C0F4101FF92F3'

        const cmd  = strHex.slice(0, 4);
       
        if (cmd === '55AA') {
        const sign = strHex.slice(-4)
        const dt = strHex.slice(0, -4)
        const sign_str = crc16(dt)
            if (sign === sign_str) {
                if (strHex.toUpperCase().startWith(`55AA${ctx.data.id}0102550333060708`)) {
                    ctx.setData({
                        isLink: true,
                    })
                } else if (strHex.toUpperCase().startWith(`55AA${ctx.data.id}0000840100000000`)) {
                    ctx.setData({
                        isTranslate: true,
                    })
                } else {
                    ctx.setData({
                        isLink: false,
                        isTranslate: false,
                    })
                }
            }
        }

    },
    linkHandler() {
        let data = '55CC'
        data += this.data.id
        data += '0102CC04AA060708'
        data += crc16(data)
        sendData = data
        this.btSendTap()
    },
    chooseFile() {
        wx.chooseMessageFile({
            type: 'file',
            count: 1,
            extension: ['hex'],
            success(res){
                console.log(res)
                ctx.setData({
                    chooseFile: res.tempFiles[0]
                })
            }
        })
    },
      updateOta() {
    if (!ctx.data.chooseFile) {
      ecUI.showToast('请选择升级文件')
      return
    }
     if (!ctx.data.isLink) {
      ecUI.showToast('请先连接设备')
      return
    }
    const filemgr = wx.getFileSystemManager()
    const targetPath = wx.env.USER_DATA_PATH

    try {
    //   const resFile = filemgr.readFileSync(targetPath + `/${ctx.data.fileName}`, 'hex')
      const resFile = filemgr.readFileSync(ctx.data.chooseFile.path, 'hex')
      // let rrdata = res.data
      let totalCount = Math.ceil(resFile.length / (256 * 2))
      ctx.setData({
        updataHex: resFile, //string格式的数据放这里
        totalCount: totalCount,
        curPkg: 0
      }, () => {
        // console.log(crc32(hexCharCodeToStr(ctx.data.updataHex)).toString(16).toUpperCase())
      })



      const resFileLen = endianConv(dec2hex(resFile.length / 2, 8))

      const fnArr = ctx.data.fileName.split('V')
      const v = extractNumbers(fnArr[fnArr.length - 1])
      const str = v.map( ele => dec2hex(ele, 2)).join('')
      const resFileName = endianConv(padHex(`${str}`, 16))

      // console.log('resFileLen', resFileLen)
      // console.log('resFileName', resFileName)

      const code = `B55B17AA${dec2hex(this.data.curPkg, 4)}${resFileLen}${resFileName}`
      const sign = checkEnd(`AA${dec2hex(this.data.curPkg, 4)}${resFileLen}${resFileName}`)
      const data = code + sign
      log(`发送第0个分片 data ===> ${data}`)

      ecBLE.writeBLECharacteristicValue(data, true)
    } catch (e) {
      console.log('升级失败', e)
      ecUI.showToast(e)
    }

  },
     nextPkg(nextAddr) {
    // const curPkg = ctx.data.curPkg
    let dataPart
    if (nextAddr !== ctx.data.totalCount) {
      dataPart = ctx.data.updataHex.slice((nextAddr - 1) * 256 * 2, nextAddr * 256 * 2)
    } else {
      dataPart = ctx.data.updataHex.slice((nextAddr - 1) * 256 * 2)
    }

    // dataPart = padHex(dataPart, 128)
    let dataLen = dataPart.length / 2

    const code = `B55B${padHex(dec2hex(dataLen + 1 + 2), 1)}AA${endianConv(dec2hex(nextAddr, 4))}${dataPart}`
    const sign = checkEnd(`AA${endianConv(dec2hex(nextAddr, 4))}${dataPart}`)
    const data = code + sign
    log(`发送第${nextAddr}个分片 data ===> ${data}`)
    ecBLE.writeBLECharacteristicValue(data, true)
    Timer2 = setTimeout(() => {
      if (count < 5) {
        count++
        ctx.nextPkg(nextAddr)
      } else {
        clearTimeout(Timer2)
        count = 0
        log('升级文件传输失败')
        ecUI.showToast('升级文件传输失败')
      }
    }, 1000)
  },

  endPkg() {
    const crc = endianConv(crc32(hexCharCodeToStr(ctx.data.updataHex)).toString(16).toUpperCase())
    const code = `B55B07AAFFFF${crc}`
    const sign = checkEnd(`AAFFFF${crc}`)
    const data = code + sign
    log(`发送最后一个分片 data ===> ${data}`)
    ecBLE.writeBLECharacteristicValue(data, true)
  },
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
        ecBLE.onBLEConnectionStateChange(() => { })
        ecBLE.onBLECharacteristicValueChange(() => { })
        ecBLE.closeBLEConnection()
        clearInterval(T1)
        T1 = null
    },
    onHide() {
        ecBLE.onBLEConnectionStateChange(() => { })
        ecBLE.onBLECharacteristicValueChange(() => { })
        clearInterval(T1)
        T1 = null
    },
    btSendTap() {
            let data = sendData
                .replace(/\s*/g, '')
                .replace(/\n/g, '')
                .replace(/\r/g, '')
            if (data.length === 0) {
                ecUI.showModal('提示', '请输入要发送的数据')
                return
            }
            if (data.length % 2 != 0) {
                ecUI.showModal('提示', '数据长度只能是双数')
                return
            }
            if (data.length > 488) {
                ecUI.showModal('提示', '最多只能发送244字节')
                return
            }
            if (!new RegExp('^[0-9a-fA-F]*$').test(data)) {
                ecUI.showModal('提示', '数据格式错误，只能是0-9,a-f,A-F')
                return
            }
            console.log('sendData====>', sendData)
            ecBLE.writeBLECharacteristicValue(data, true)
    },
})
